// api路由
// userApi.js —— 测试用 API 示例

/* eslint-disable */
var models = require('../db');
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var $sql = require('../sqlMap');
var fs = require('fs')
// 连接数据库
var conn = mysql.createConnection(models.mysql);
conn.connect();
var jsonWrite = function (res, ret) {
    if (typeof ret === 'undefined') {
        res.json({
            code: '1', msg: '操作失败'
        });
    }
    else {
        res.json(
            ret
        );
    }
};

//数据库添加组件接口
router.post('/addComponent', (req, res) => {
    var sql = $sql.component.add;
    var params = req.body;
    console.log(params);

    //userId为用户ID
    const userId = params.user_id;
    const savePath = './static/data_' + userId + '.json';
    if(!fs.existsSync('./static')) fs.mkdirSync('./static');
    const outStream = fs.createWriteStream(savePath);
    outStream.write(JSON.stringify(params.user_data),'utf8');
    console.log('文件写入完毕。');
    outStream.close();

    conn.query(sql, [userId, savePath], function (err, result) {
        if (err) {
            console.log(err);
        }
        if (result) {
            jsonWrite(res, result)
        }
    })
}),

// 增加用户接口
router.post('/addUser', (req, res) => {
    var sql = $sql.user.add;
    var params = req.body;
    console.log(params);
    conn.query(sql, [params.username, params.password], function (err, result) {
        if (err) {
            console.log(err);
        }
        if (result) {
            jsonWrite(res, result)
        }
    })
});


// 查询组件
router.get('/queryComponent', (req, res) => {
    var sql = $sql.component.query;
    var params = req.body;
    conn.query(sql, function (err, row) {
        if (err) {
            console.log(err)
        }
        console.log(typeof row)
        let data = JSON.stringify(row)
        res.end(data)
    })
});


// 删除表
router.get('/delete', (req, res) => {
    var sql = $sql.common.delete;
    var params = req.body;
    //无表则先创建表
    conn.query($sql.base.createTable);
    conn.query(sql, function (err, row) {
        if (err) {
            console.log(err)
        }
        console.log(typeof row)
        let data = JSON.stringify(row)
        res.end(data)
    })
});

router.get('/query', (req, res) => {
    conn.query('select * from test', function (err, row) {
        if (err) {

            console.log(err)
        }
        console.log(typeof row)
        let data = JSON.stringify(row)
        res.end(data)
    })
})

module.exports = router
